package com.symbio.ishenapi.background.util;


import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;


import java.io.*;
import java.net.*;
import java.text.SimpleDateFormat;
import java.util.*;

public class HttpUtils {
	 //Log log = new Log(this.getClass());//初始化日志类	
	protected static final org.apache.commons.logging.Log logger = org.apache.commons.logging.LogFactory
			.getLog(HttpUtils.class);
	
	private static final int HTTP_TIMEOUT = 10000;
	
	/*** HTTP 超时设置 ***/
	private static final int HTTP_REQ_TIME = 3;
	
	/*** HTTP 允许请求次数 ***/
	private static final String HTTP_METHOD = "POST";

	public static String requestBss(String bssPath) {
		if (!bssPath.startsWith("/")) {
			bssPath = "/" + bssPath;
		}
		String REQ_BSS_URL = "http://" + PropertiesUtils.getProperty("BssServerIP") + bssPath;
		logger.info("REQ_BSS_URL =>>> " + REQ_BSS_URL);
		return requestHttp(REQ_BSS_URL);
	}

	@SuppressWarnings("finally")
	public static String requestHttp(String httpURL) {
		HttpURLConnection conn = null;
		BufferedReader reader = null;
		String response = "";
		try {
			for (int i = 0; i < HTTP_REQ_TIME; i++) { /***
														 * 有时候HTTP会请求失败,所以需要重复请求
														 ***/
				String str = "";
				conn = (HttpURLConnection) new URL(httpURL).openConnection(java.net.Proxy.NO_PROXY);
				conn.setReadTimeout(HTTP_TIMEOUT);
				conn.setRequestMethod(HTTP_METHOD);
				conn.setConnectTimeout(HTTP_TIMEOUT);
				reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
				while ((str = reader.readLine()) != null) {
					response += str;
				}
				if (!"".equals(response)) {
					break;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("BSS ERROR -> " + e.getMessage());
		} finally {
			try {
				reader.close(); /*** 关闭连接 ***/
				conn.disconnect(); /*** 关闭连接 ***/
			} catch (Exception e) {
				logger.error("关闭  HTTPCONNECTION 异常 -> " + e.getMessage());
			} finally {
				return response;
			}
		}
	}

	@SuppressWarnings("finally")
	public static String requestHttp(String httpURL, String HttpMethod) {
		HttpURLConnection conn = null;
		BufferedReader reader = null;
		if (StringUtil.isNullOrEmpty(HttpMethod) || (!"POST".equals(HttpMethod) && !"GET".equals(HttpMethod))) {
			HttpMethod = "POST";
		}

		String response = "";
		try {
			for (int i = 0; i < HTTP_REQ_TIME; i++) { /***
														 * 有时候HTTP会请求失败,所以需要重复请求
														 ***/
				String str = "";
				conn = (HttpURLConnection) new URL(httpURL).openConnection(java.net.Proxy.NO_PROXY);
				conn.setReadTimeout(HTTP_TIMEOUT);
				conn.setRequestMethod(HTTP_METHOD);
				conn.setConnectTimeout(HTTP_TIMEOUT);
				reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
				while ((str = reader.readLine()) != null) {
					response += str;
				}
				if (!"".equals(response)) {
					break;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("BSS ERROR -> " + e.getMessage());
		} finally {
			try {
				reader.close(); /*** 关闭连接 ***/
				conn.disconnect(); /*** 关闭连接 ***/
			} catch (Exception e) {
				logger.error("关闭  HTTPCONNECTION 异常 -> " + e.getMessage());
			} finally {
				return response;
			}
		}
	}
	
	
	 public static String sendPost(String url, String param) {
	        PrintWriter out = null;
	        BufferedReader in = null;
	        String result = "";
		 	String time = getDateTime();
	        try {
	            URL realUrl = new URL(url);
	            // 打开和URL之间的连接
				URLConnection conn = realUrl.openConnection();
				String params ="N00000033612:"+time;
				System.out.println("加密前:"+params);
				String auth = Base64Util.encode(params);
				System.out.println("加密后:"+auth);
	            // 设置通用的请求属性
	            conn.setRequestProperty("accept", "application/json");
	            conn.setRequestProperty("Content-Type", "application/json;charset=utf-8;");
	            conn.setRequestProperty("Authorization",auth);
	            // 发送POST请求必须设置如下两行
	            conn.setDoOutput(true);
	            conn.setDoInput(true);
	            // 获取URLConnection对象对应的输出流
	            out = new PrintWriter(conn.getOutputStream());
	            // 发送请求参数
	            out.print(param);
	            // flush输出流的缓冲
	            out.flush();
	            // 定义BufferedReader输入流来读取URL的响应
	            in = new BufferedReader(
	                    new InputStreamReader(conn.getInputStream(),"utf-8"));
	            String line;
	            while ((line = in.readLine()) != null) {
	                result += line;
	            }
	        } catch (Exception e) {
	            System.out.println("发送 POST 请求出现异常！"+e);
	            e.printStackTrace();
	        }
	        //使用finally块来关闭输出流、输入流
	        finally{
	            try{
	                if(out!=null){
	                    out.close();
	                }
	                if(in!=null){
	                    in.close();
	                }
	            }
	            catch(IOException ex){
	                ex.printStackTrace();
	            }
	        }
	        return result;
	    }    
	 
	 
	 
	 public static String sendPosts(String url, String data) {
		          String response = null;
		         //log.info("url: " + url);
		          //log.info("request: " + data);
		          try {
		             CloseableHttpClient httpclient = null;
		              CloseableHttpResponse httpresponse = null;
		              try {
		                 httpclient = HttpClients.createDefault();
		                 HttpPost httppost = new HttpPost(url);
		                 StringEntity stringentity = new StringEntity(data,
		                         ContentType.create("text/html", "UTF-8"));
		                 httppost.setEntity(stringentity);
		                 httpresponse = httpclient.execute(httppost);
		                 response = EntityUtils
		                        .toString(httpresponse.getEntity());
		                 //log.info("response: " + response);
		             } finally {
		                 if (httpclient != null) {
		                     httpclient.close();
		                 }
		                 if (httpresponse != null) {
		                     httpresponse.close();
		                 }
		             }
		         } catch (Exception e) {
		             e.printStackTrace();
		        }
		         return response;
		     }
	 
	 public static String requestPost(String strUrl, String param) {
	        String returnStr = null; // 返回结果定义
	        URL url = null;
	        HttpURLConnection httpURLConnection = null;
	 
	        try {
	            url = new URL(strUrl);
	            httpURLConnection = (HttpURLConnection) url.openConnection();
	            httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");
	            httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
	            httpURLConnection.setDoOutput(true);
	            httpURLConnection.setDoInput(true);
	            httpURLConnection.setRequestMethod("POST"); // post方式
	            httpURLConnection.connect();
	            //System.out.println("ResponseCode:" + httpURLConnection.getResponseCode());
	            //POST方法时使用
	            byte[] byteParam = param.getBytes("UTF-8");
	            DataOutputStream out = new DataOutputStream(httpURLConnection.getOutputStream());
	            out.write(byteParam);
	            out.flush();
	            out.close();
	            BufferedReader reader = new BufferedReader(
	                    new InputStreamReader(httpURLConnection.getInputStream(), "utf-8"));
	            StringBuffer buffer = new StringBuffer();
	            String line = "";
	            while ((line = reader.readLine()) != null) {
	                buffer.append(line);
	            }
	 
	            reader.close();
	            returnStr = buffer.toString();
	        } catch (Exception e) {
	            e.printStackTrace();
	            return null;
	        } finally {
	            if (httpURLConnection != null) {
	                httpURLConnection.disconnect();
	            }
	        }
	        return returnStr;
	    }
	public static String getDateTime(){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		return sdf.format(new Date());
	}


	public static JSONObject sendPostt(String url, String outUrl) {
			JSONObject jsonObject=null;
			CloseableHttpClient httpClient = HttpClients.createDefault();
			HttpPost httpPost = new HttpPost();
			httpPost.setHeader("Content-Type","application/x-www-form-urlencoded");
			httpPost.setEntity(new StringEntity(outUrl,"UTF-8"));
			URI uri = null;
			try {
				uri = new URI(url);//视频中忘了加url，所以输出httpPost，会显示POST null HTTP/1.1
			}
			catch (URISyntaxException e1) {
				e1.printStackTrace();
			}
			httpPost.setURI(uri);
			System.out.println(httpPost);//POST null HTTP/1.1
			try {
				HttpResponse reponse = httpClient.execute(httpPost);
				String result = EntityUtils.toString(reponse.getEntity(),"UTF-8");
				System.out.println(result);
				jsonObject=JSONObject.fromObject(result);
				System.out.println(jsonObject);
			}
			catch (ClientProtocolException e) {
				e.printStackTrace();
			}
			catch (IOException e) {
				e.printStackTrace();
			}

			return jsonObject;
		}



    public static String doPost(String url, Map<String,String> map, String charset) {
        HttpClient httpClient = null;
        HttpPost httpPost = null;
        String result = null;
        try {
            httpClient = new SSLClient();
            httpPost = new HttpPost(url);
            // 设置参数
            List<NameValuePair> list = new ArrayList<NameValuePair>();
            Iterator iterator = map.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, String> elem = (Map.Entry<String, String>) iterator.next();
                list.add(new BasicNameValuePair(elem.getKey(), elem.getValue()));
            }
            if (list.size() > 0) {
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list,charset);
                httpPost.setEntity(entity);
            }
            HttpResponse response = httpClient.execute(httpPost);
            if (response != null) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    result = EntityUtils.toString(resEntity,charset);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return result;
    }
}